/*
 * navTab single-form v1.0 Copyright(c) 2016.6 by CSS WeidongWang
 */
function navTabSearch(form, navTabId){
	$navTab.submitForm(form);
	return false;
}
function tabModel(){
		id="";
		title="";
		url="";
		content="";
		formInput="";
		formParams="";
		extraFlag=false;
		tabWidth=0;
}
;(function($){
	var map = {},
			maxLength = 30,
			homeTabId,
			curTab,
			methods = {
				init: function(inTab){
					homeTabId = inTab.id;
					curTab  = inTab;
					curTab.content=$content.html();
					map[curTab.id]=curTab;
					methods.initClick();
				},
  			initClick: function(){
					$a=$ul.find('[href="#' + curTab.id + '"]');
					$a.on('click', methods.event.click);
					curTab.tabWidth=$a.outerWidth(true);
					$more.next().append('<li id="moreBtnLi' + curTab.id + '"><a href="javascript:;">'+curTab.title+'</a></li>');
 					$more.next().on('click','li',function(){
          	var index=$more.next().find('li').index(this);
          	$ul.find('> li a').eq(index).click();
        	});
  				methods.contextMenu($ul.find('a'));
				},				
        loadTab: function(){
        	if(curTab.extraFlag){
        		var ih = $content.height() - 5;
        		var data='<div id="' + curTab.id + '" class="tab-pane"><iframe src="' + curTab.url + '" style="margin:0;padding0;overflow:hidden;width:100%;height:' + ih + 'px;" frameborder="no" border="0" marginwidth="0" marginheight="0"></iframe></div>';
						writeResult(data);
        	}
        	else
        		methods.ajaxFun(curTab.url,curTab.formParams);
				}, 
        ajaxFun: function(url,param){
        	$content.html('<center><div class="ptLoading">加载中...</div></center>');
        	$.post(url,param,function(data){
            methods.writeResult(data);
					})
        },
				writeResult: function(data){
					curTab.content=data;
					$content.html(data);
					methods.showTab();
				},
				showTab:function(){
					$ul.find('[href="#' + curTab.id + '"]').tab('show');
	      	methods.scrollCurrent();
	      },
	      event: {
	        click: function(e) {
	         	var key=$(this).attr('tabid');
	          if(key == curTab.id)
	          	return;
						methods.saveForm();
						curTab = map[key];
	        	methods.writeResult(curTab.content);
	        	methods.loadForm();
	        },
	        close: function(e) {
	          var key=$(this).parent().attr('tabid');
	          $navTab.closeTab(key);
	        }
      	},
        closeOther: function (key) {
        	for(tmpKey in map){
        		if(tmpKey!=key)
        			$navTab.closeTab(tmpKey);
					}
        },
        closeAll: function () {
        	for(tmpKey in map)
        		$navTab.closeTab(tmpKey);
        },
        contextMenu: function($obj) {
	        $obj.cssMenu({
	          selector: '#' + $ul.attr('context-menu'),
	          callback: {
	            close: function(t) {
	              $navTab.closeTab(t.attr('tabid'));
	            },
	            closeOther: function(t) {
	              methods.closeOther(t.attr('tabid'));
	            },
	            closeAll: function(t) {
	              methods.closeAll();
	            },
	            reload: function(t) {
	              $navTab.refreshTab(t.attr('tabid'));
	            }
	          }
	        });
      	},
	     	getNextTab:function(key){
      		var length  = Object(map).length;
      		if(length<1) return '';
      		var nextTabId='', left=1;
      		for(tmpKey in map){
      			if(left<1) return tmpKey;
      			if(tmpKey==key)
      				left--;
      			else
      				nextTabId=tmpKey;
					}
					return nextTabId;
      	},
	      scrollTab: function(iLeft, isNext){
	        $ul.animate({ marginLeft: iLeft+'px' }, 200, function(){});
	      },
       currentPos: function(){
	      	var cw=0;
	      	for(tmpKey in map){
	      		tmpTab = map[tmpKey];
	      		cw+=tmpTab.tabWidth;
	      		if(tmpKey==curTab.id)
	      			break;
					}
					return cw;
	      },
	      scrollCurrent: function(){
	      	var barw = $module.width(); 
	      	var cw = methods.currentPos();
	      	methods.scrollTab(cw <= barw -15?0:(barw-cw-100));
	      },    	
				loadForm:function(){
					try{var name="";
						$.each(curTab.formInput, function () {
							name=this.name.replace('\.','\\.');
							var obj= $('#'+name);
							if(obj.is('input')){
								if(obj.attr('type').toLowerCase() == 'checkbox'){
									$("input:checkbox[value='"+this.value+"']").attr('checked','true')
								}else if(obj.attr('type').toLowerCase() == 'radio'){
									$("input:radio[value='"+this.value+"']").attr('checked','true')
								}else{
									obj.val(this.value);
								}
							}else{
								obj.val(this.value);
							}
						});
					}catch(e){}
				},
	      saveForm:function(){
	      	try{
	      	curTab.content = $content.html();
	        curTab.formInput = $('.table-form').serializeArray();
	     	 }catch(e){}
	      }
    	};
  $navTab = {
    event: function(){
      $('body').on('click','[target=cssTab]',function(){
		    var $this=$(this),
		    	  tab=new tabModel();
				tab.id=$this.attr('rel');
				tab.title=$this.attr('title')?$this.attr('title'):$this.html();
				tab.url=$this.attr('href');
				$navTab.openTab(tab);
		    return false;
			})  
    },
    init:function(el,tabInfo){
    	$module = $(el);
      $ul = $module.find('.nav-tabs');
      $more = $module.find('.more'),
      $content = $module.find('.tab-content');
      methods.init(tabInfo);
    },
		openTab: function (tabInfo) {
 			var has = tabInfo.id in map;
 			if(has){
 				curTab = map[tabInfo.id];
 				curTab.formParams='';
 				curTab.url=tabInfo.url;
		    methods.loadTab();
 			}else{
 				var length  = Object(map).length;
				if(length >= maxLength){
					alert("最多可以打开"+maxLength+"个标签！");
					return;
				}
		    curTab=tabInfo;
		    map[curTab.id]=tabInfo;
				$li = $('<li id="myTabli' + tabInfo.id + '"><a tabid="' + tabInfo.id + '" href="#' + tabInfo.id + '"><span>' + tabInfo.title + '</span><i class="remove"></i></a></li>');
		    $ul.append($li);
		    $li.find('a .remove').on('click', methods.event.close);
				methods.initClick();
		    methods.loadTab();
			}
   	}, 
    closeCurrentTab: function() {
    	$navTab.closeTab(curTab.id);
    },
	 	closeTab:function(tabId){
	    if(tabId == homeTabId) return;
 			if(!(tabId in map))	return;
 	    var nextTabId=methods.getNextTab(tabId);
	    delete map[tabId];
	    $('#myTabli'+tabId).remove();
		  $('#moreBtnLi'+tabId).remove();
		    if(nextTabId !=''){
			  	curTab=map[nextTabId];
	        methods.writeResult(curTab.content);
			  }
		},
    refreshCurrentTab: function() {
    	methods.loadTab();
    },
    refreshTab: function(tabId) {
 			if(!(tabId in map))	return;
 			curTab = map[tabId];
  		methods.loadTab();
    },
    getCurrentTab: function() {
    	return curTab;
    },
    getTab: function(tabId) {
 			if(!(tabId in map))	return '';
    	return map[tabId];
    },
    submitForm: function(form){
			curTab.formParams=$(form).serialize();
  		$navTab.ajaxLoadForm($(form).attr('action'),$(form).serialize(),$(form).parent());
   	},
   	ajaxLoadForm: function(url, param, parent){
    	$.post(url,param,function(data){
			  parent.html(data);
			})
    }
  };
})(jQuery)